<?php
Yii::import('Site.models.*');
class CategoryController extends BackOfficeController
{
    /**
     * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */
    public $layout = '//layouts/column2';

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate()
    {
        $this->actionUpdate();
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate()
    {
        if (Yii::app()->request->IsPostRequest) {
            // save posted data
            $_POST['validateOnly'] = ($this->post('ajax', '') == 'category-form');
            $result = FSM::run('Core.Category.save', $_POST);
            $model = $result->model;

            if ($this->post('ajax', '') == 'category-form') {
                echo $result->getActiveErrorMessages($result->model);
                Yii::app()->end();
            }
            if (!$result->hasErrors()) {

                //Begin saving tabula input:
                //Find all language category saved in database with curren category id
                $languageCategory = LanguageCategory::model()->findAllByAttributes(array(
                    'category_id' => $model->id,
                ));
                if (!$languageCategory) {
                    $langList = Language::model()->findAll('status=1');
                    if (count($langList)) {
                        foreach ($langList as $i => $lang) {
                            $languageCategory[$i] = new LanguageCategory();
                            $languageCategory[$i]->category_id = $model->id;
                        }
                    }

                }

                $valid = true;
                foreach ($languageCategory as $i => $item) {
                    if (isset($_POST['LanguageCategory'][$i]))
                        $item->attributes = $_POST['LanguageCategory'][$i];
                    $valid = $item->validate() && $valid;
                }

                if ($valid) { // all items are valid
                    // ...save all setting
                    foreach ($languageCategory as $i => $item) {
                        $item->attributes = $_POST['LanguageCategory'][$i];
                        $item->save();
                    }
                }
                //End saving tabula input

                $this->message = Yii::t('Core', 'Item has been saved successfully.');
                $this->redirect(array('update', 'id' => $model->id));
            }
        } else {
            // show edit form
            $id = $this->get('id', 0);
            if ($id == 0) {
                $model = new Category();
            } else {
                $model = FSM::run('Core.Category.get', array('id' => $id))->model;
            }
        }

        $this->render('update', array('model' => $model));
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete($id)
    {
        if (Yii::app()->request->isPostRequest) {
            // we only allow deletion via POST request
            if (($id = $this->get('id', null)) !== null) {
                $ids = is_numeric($id) ? array($id) : explode(',', $id);

                // delete one or multiple objects given the list of object IDs
                $result = FSM::run('Core.Category.delete', array('ids' => $ids));
                if ($result->hasErrors()) {
                    echo $result->getError('ErrorCode');
                } elseif (!Yii::app()->request->isAjaxRequest) {
                    // only redirect user to the admin page if it is not an AJAX request
                    $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
                }
            } else {
                throw new CHttpException(400, Yii::t('Core', 'Cannot delete item with the given ID.'));
            }
        } else {
            throw new CHttpException(400, Yii::t('Core', 'Invalid request. Please do not repeat this request again.'));
        }
    }

    /**
     * Lists all models.
     */
    public function actionIndex()
    {
        $this->actionAdmin();
    }

    /**
     * Manages all models.
     */
    public function actionAdmin()
    {
        $model = new Category('search');
        $model->unsetAttributes(); // clear any default values
        if (isset($_GET['Category']))
            $model->attributes = $_GET['Category'];

        $criteria = new CDbCriteria;
        $criteria->compare('parent_id', 0);
        $criteria->order = 'ordering';
        $models = Category::model()->findAll($criteria);

        Yii::import('Core.utilities.*');
        $this->render('admin', array(
            'models' => $models,
        ));
    }

    protected function renderNestedCategory($viewFile, $models)
    {
        foreach ($models as $index => $model) {
            echo '<li class="sortable" id="items-' . $model->id . '">';
            Yii::app()->controller->renderFile($viewFile, array('class' => 'odd', 'model' => $model));
            $children = $model->children;
            if (is_array($children) && count($children)) {
                echo '<ul>';
                $this->renderNestedCategory($viewFile, $children);
                echo '</ul>';
            }
            echo '</li>';
        }
    }
}
